package com.beiding.dao.impl;

import com.beiding.dao.AuthorityDao;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SetOperations;
import org.springframework.stereotype.Repository;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Repository
public class AuthorityDaoImpl implements AuthorityDao {


    //某个用户所具有的权限
    private SetOperations<String, String> set;

    public AuthorityDaoImpl(RedisTemplate<String, String> redisTemplate) {
        set = redisTemplate.opsForSet();
    }

    @Override
    public void add(String username, String authority) {
        set.add("manager_authority:" + username, authority);
        set.add("manager_user", username);
    }

    @Override
    public Map<String, Set<String>> getAll() {

        Set<String> managerUser = set.members("manager_user");

        Map<String, Set<String>> r = new HashMap<>();


        managerUser.forEach(s -> {

            Set<String> members = set.members("manager_authority:" + s);


            if (members.size() == 0) {
                set.remove("manager_user", s);
            } else {
                r.put(s, members);
            }

        });


        return r;
    }

    @Override
    public void remove(String username, String authority) {

        //移除权限
        set.remove("manager_authority:" + username, authority);

    }


}
